package com.trainoo.novel.crawler;

import com.trainoo.novel.constant.NovelConstant;
import com.trainoo.novel.model.Book;
import com.trainoo.novel.model.Chapter;
import com.trainoo.novel.util.UrlDownLoader;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.*;

/**
 * @Auther: zt
 * @Date: 2019/12/18 16:37
 * @Description:
 */
@Component
public class XssNovelCrawler extends NovelCrawlerAdapter{

    private static Logger logger = LoggerFactory.getLogger(XssNovelCrawler.class);

    @Value("${base.url.xss}")
    private String BASE_URL;

    @Value("${search.url.xss}")
    private String SEARCH_URL;

    @Override
    public Book crawlBookInfo(String bookId) {
        // 返回结果集
        Book book = new Book();

        Document doc = UrlDownLoader.download(BASE_URL + "/files/article/info/1/" + bookId + ".html");

        Element bookdetail = doc.getElementById("bookdetail");
        for (Element a: bookdetail.getElementsByTag("a")){
            a.attr("href", "javascript:void(0)");
        }
        String bookName = bookdetail.getElementById("info").getElementsByTag("h1").get(0).html();
        book.setBookName(bookName);
        book.setMainInfo(bookdetail.html());

        Element list = doc.getElementById("list");
        List<Chapter> chapList = new ArrayList<>();
        for(Element chapter: list.getElementsByTag("a")){
            String chapterUrl = "/book/" + bookId + "/" + chapter.attr("href").split("/")[6];
            String chapterName = chapter.html();
            Chapter chap = new Chapter(chapterName, URLEncoder.encode(chapterUrl));
            chapList.add(chap);
        }
        book.setChapters(chapList);
        return book;
    }

    @Override
    public Chapter readChapter(String url) {
        Document doc =  UrlDownLoader.download(BASE_URL + "/files/article/html/1/" + url);
        String title = doc.getElementsByClass("bookname").get(0).getElementsByTag("h1").text();
        String content = doc.getElementById("content").html();
        String prev = doc.getElementsByClass("pre").get(0).attr("href");
        String chap = doc.getElementsByClass("back").get(0).attr("href");
        String next = doc.getElementsByClass("next").get(0).attr("href");

        // 需要处理第一章跟最后一章的特殊情况
        String chapNew = "/book/" + chap.split("/")[5];
        prev = chap.equals(prev) ? chap : ("/book/" + prev.split("/")[5] + "/" + prev.split("/")[6]);
        next = chap.equals(next) ? chap : ("/book/" + next.split("/")[5] + "/" + next.split("/")[6]);

        Chapter chapter = new Chapter();
        chapter.setPreUrl(prev);
        chapter.setChapMain(chapNew);
        chapter.setNextUrl(next);
        chapter.setChapName(title);
        chapter.setContent(content);
        logger.info("正在加载内容[{}]", title);
        return chapter;
    }

    @Override
    public List<Chapter> hotBookList() {
        Document doc = UrlDownLoader.download(BASE_URL);
        Elements aList = doc.getElementsByTag("a");
        List<Chapter> hotList = new ArrayList<>();
        Set<String> urls = new HashSet<>();
        for (int i = 0; i < aList.size(); i++) {
            String html = aList.get(i).html();
            String href = aList.get(i).attr("href");
            if (!html.contains("img") && href.contains(".html") && href.contains("/files/article/info")){
                // 使用set去重
                if(urls.add(href)){
                    href = "/book/" + href.split("/")[5].replace(".html", "");
                    hotList.add(new Chapter(html, href));
                }
            }
        }
        return hotList;
    }

    @Override
    public List<Book> searchBook(Map<String, String> contentMap) {
        String keyWord = contentMap.get(NovelConstant.KEY_WORD);
        Document doc = UrlDownLoader.download(SEARCH_URL + "&name=" + keyWord);
        List<Book> resultList = new ArrayList<>();
        try {
            Elements lists = doc.getElementsByClass("novelslist2").get(0).getElementsByTag("li");
            // 第一行是标题，跳过第一行
            for(int i=1; i < lists.size(); i++){
                Element element = lists.get(i);

                String bookName = element.getElementsByClass("s2").get(0).getElementsByTag("a").get(0).text();
                String authName = element.getElementsByClass("s4").get(0).getElementsByTag("a").get(0).text();
                String bookUrl = element.getElementsByClass("s2").get(0).getElementsByTag("a").get(0).attr("href");
                String newName = element.getElementsByClass("s3").get(0).getElementsByTag("a").get(0).attr("title");
                String newUrl = element.getElementsByClass("s3").get(0).getElementsByTag("a").get(0).attr("href");

                Book book = new Book();
                book.setBookDesc("暂无简介");
                book.setAuthName(authName.replace("作者：", ""));
                book.setBookUrl("/book/" + bookUrl.split("/")[5].replace(".html", ""));
                book.setBookName(bookName);
                book.setNewName(newName);
                book.setNewUrl("/book/" + newUrl.split("/")[5] + "/" + newUrl.split("/")[6]);
                resultList.add(book);
            }
        } catch (Exception e){
            logger.error("查询图书出现异常", e);
        }
        return resultList;
    }
}
